package com.dark.controller.user;

import com.dark.base.FlowerFallingErrorCodeEnmu;
import com.dark.base.FlowerFallingException;
import com.dark.base.Result;
import com.dark.controller.BaseController;
import com.dark.model.dto.ChangePasswordDto;
import com.dark.util.AssertUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.dark.model.dto.LoginDto;
import com.dark.model.dto.RegisterDto;
import com.dark.model.po.User;
import com.dark.model.vo.UserVo;
import com.dark.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * ClassName: LoginController
 * Description:LoginController
 *
 * @author chengluchao
 * @date: 2022/8/13 3:13 PM
 * @since 1.4.8
 */
@Slf4j
@Api(tags = "用户模块：注册，登陆，改密码，维护个人信息...")
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    @Resource
    IUserService userService;


    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "登陆")
    @PostMapping("login")
    @ResponseBody
    public Result<UserVo> login(@RequestBody @Validated LoginDto dto) {
        log.info("{}登陆", dto.getAccount());
        User user = userService.lambdaQuery().eq(User::getAccount, dto.getAccount()).one();
        AssertUtil.assertNouNull(user, FlowerFallingErrorCodeEnmu.LOGIN_INFORMATION_ERROR);
        String pwd = userService.generatePassword(dto.getPwd(), user.getUuid());
        if (!pwd.equals(user.getPwd())) {
            throw new FlowerFallingException(FlowerFallingErrorCodeEnmu.LOGIN_INFORMATION_ERROR);
        }
        String token = getToken(user);
        // 反写cookie
        settingToken(token, user);
        // 将user的信息返回给客户端，可以减少一次接口查询
        UserVo vo = new UserVo();
        BeanUtils.copyProperties(user,vo);
        return new Result<>(vo);
    }
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取用户信息")
    @PostMapping("geUser")
    @ResponseBody
    public Result<UserVo> geUser() {
        User user = getUserInfo();
        UserVo vo = new UserVo();
        BeanUtils.copyProperties(user,vo);
        return new Result<>(vo);
    }

/*    @Value("${jjc.user.default.enable:false}")
    public void init(boolean enable) {
        if (enable) {
            User user = userService.getById(17);
            settingToken("7a6743e5b7d98c00eba347dd9f9c8e1c", user);
        }
    }*/

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "注册")
    @PostMapping("register")
    @ResponseBody
    public Result<User> register(@Validated @RequestBody RegisterDto dto) {
        // check user
        this.assertUserdoNotConflict(dto);
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        userService.register(user);
        return new Result<>(user);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "修改密码")
    @PostMapping("changePassword")
    @ResponseBody
    public Result<User> changePassword(@Validated @RequestBody ChangePasswordDto dto) {
        // 缓存中获取单点用户信息
        User user = getUserInfo();
        // 查询数据库中完整且准确的数据
        user = userService.getById(user.getId());
        String pwd = userService.generatePassword(dto.getOldPwd(), user.getUuid());
        AssertUtil.assertTrue(Objects.equals(user.getPwd(), pwd), FlowerFallingErrorCodeEnmu.THE_ORIGINAL_PASSWORD_IS_WRONG);
        user.setPwd(userService.generatePassword(dto.getNewPwd(), user.getUuid()));

        userService.updateById(user);
        return new Result<>(user);
    }


    private void assertUserdoNotConflict(RegisterDto dto) {
        if (!CollectionUtils.isEmpty(userService.lambdaQuery().eq(User::getAccount, dto.getAccount()).list()))
            throw new FlowerFallingException(FlowerFallingErrorCodeEnmu.ACCOUNT_HAS_BEEN_REGISTERED);
    }
}
